import React, { ReactNode, useEffect, useRef, useState } from 'react';
import ZcoScreenSync from '../../../public/js/widget-sync-screen';
console.log('ZcoScreenSync ', ZcoScreenSync);

import Draggabilly from 'draggabilly';
import useSyncState from '../hooks/useSyncState';
import Message from '@/utils/message';
import { BusinessTaskMap, IBusinessName, IBusinessStatus, ReceiveBroadcastMap } from './BusinessContext';
import { useTranslation } from 'react-i18next';

export interface ScreenSyncStateProps {
	cmdId: number | null;
	clientId: string | null;
	messageIn: any;
	status: 'idle' | 'start' | 'connected' | 'end';
	size: IScreenSize;
	mode: 'small' | 'large';
	pageLeave: boolean;
}

interface IScreenSize {
	width: number;
	height: number;
	scrollHeight: number;
}

type IStartCoBrowsing = 'request-customer-size' | undefined;

const defaultInitialState: ScreenSyncStateProps = {
	status: 'idle',
	mode: 'small',
	messageIn: {},
	clientId: null,
	cmdId: null,
	size: {
		width: 0,
		height: 0,
		scrollHeight: 0
	},
	pageLeave: false,
};

let zcoScreenSync: any = null;

const ScreenSyncContext = React.createContext<
	| {
		zcoScreenSync: any;
		screenSyncState: () => ScreenSyncStateProps;
		setScreenSyncState: (data: any) => void;
		startCoBrowsing: (type: IStartCoBrowsing) => void;
		onCoBrowsing: () => void;
		reuqestPages: () => void;
		initScreenSync: () => void;
		onScreenSyncEnd: () => void;
	}
	| undefined
>(undefined);
ScreenSyncContext.displayName = 'ScreenSyncContext';

const ScreenSyncProvider = ({ children }: { children: ReactNode }) => {
	const { t } = useTranslation();
	const [screenSyncState, setScreenSyncState] = useSyncState<ScreenSyncStateProps>(defaultInitialState);
	const isStartScreenSync = useRef<boolean>(false);
	const [errorMessage, setErrorMessage] = useState('');

	useEffect(() => {
		setScaleSize();
		if (screenSyncState().mode === 'large') {
			const draggabilly = new Draggabilly('#widget-sync-screen-wrapper', {
				handle: '.sync-screen-tips',
				containment: '.widget-agent-container'
			});
			draggabilly.on('staticClick', function (event) {
				const className = (event.target as any).className;
				if (className && typeof className === 'string' && className.includes('interactable')) {
					return;
				}
				event.preventDefault();
				event.stopPropagation();
				console.warn('staticClick : ', (event?.target as any)?.className
				);
				const clickEvent = new MouseEvent('click', {
					view: window,
					bubbles: true,
					cancelable: true
					// remoteControl: true
				});
				event.target?.dispatchEvent(clickEvent);
			});
		}
	}, [screenSyncState().mode]);

	useEffect(() => {
		if (errorMessage) {
			Message.warning(errorMessage);
		}
	}, [errorMessage])

	const setClientId = (clientId: string) => {
		setScreenSyncState({ ...screenSyncState(), clientId });
	};

	const setSize = (size: IScreenSize) => {
		setScreenSyncState({ ...screenSyncState(), size });
	};

	const startCoBrowsing = (type: IStartCoBrowsing) => {
		if (isStartScreenSync.current) return;
		// 设置一条同屏流
		const data = type ? { type } : undefined;
		ivcs.agent.coBrowsing(
			data,
			screenSyncState().clientId || '',
			(res: any) => {
				onCoBrowsing();
				console.log('coBrowsing success', res);
				// BusinessTaskMap.updateTaskStatus(screenSyncState().clientId!, IBusinessStatus.START, null);
			},
			(error: any) => {
				console.log('coBrowsing error', error);
			}
		);
		isStartScreenSync.current = true;
	};

	const reuqestPages = () => {
		ivcs.agent.coBrowsing(
			{ type: 'request-pages' },
			screenSyncState().clientId || '',
			(res: any) => {
				const { cmdId = null } = res as any;
				setScreenSyncState({ ...screenSyncState(), cmdId: cmdId, mode: 'large', status: 'connected' });
				console.log('request-pages', res);
			},
			(error: any) => {
				console.log('request-pages', error);
			}
		);
	};

	/**
	 * 接收访客同屏数据过程/结果<目前用于坐席端同屏辅助>
	 */
	const onCoBrowsing = () => {
		console.log('onCoBrowsing');
		ivcs.agent.onCoBrowsing(async (resp: any) => {
			// 同屏消息
			console.log('onCoBrowsing:', resp);
			if (resp && resp.data && resp.data.data) {
				// 停止同屏
				if (resp.data.data.action === 'endScreenSync') {
					setScreenSyncState(defaultInitialState);
				} else if (resp.data.data.action === 'end') {
					Message.warning(t('screen-sync-session-ended'));
					console.log(BusinessTaskMap, ReceiveBroadcastMap, 'endScreenSync');
					// if (BusinessTaskMap.getTask(screenSyncState().clientId!)) {
					// 	BusinessTaskMap.updateTaskStatus(screenSyncState().clientId!, IBusinessStatus.DONE, screenSyncState().cmdId);
					// 	const task = await BusinessTaskMap.getTask(screenSyncState().clientId!);
					// 	if (task) {
					// 		await BusinessTaskMap.addCompletedTask({ task: IBusinessName.FACE_COMPARE, data: task, response: {}, isRead: false });
					// 	}
					// }
					setScreenSyncState(defaultInitialState);
				} else if (resp.data.data.action === 'size') {
					setScreenSyncState({ ...screenSyncState(), size: resp.data.data.value });
					initScreenSync();
				} else {
					console.log('setMessageIn:', resp.data.data, screenSyncState);
					setScreenSyncState({ ...screenSyncState(), messageIn: resp.data.data });
					if (zcoScreenSync) {
						zcoScreenSync.setMessageIn(resp.data.data);
					}
					setErrorMessage('');
				}
				if (zcoScreenSync && resp.data.data.action !== 'endScreenSync' && resp.data.data.action !== 'size') {

				}
			}
		});
	};

	/** 设置小屏模式下同屏尺寸 */
	const setScaleSize = () => {
		const screenCotnianer = document.getElementById('widget-sync-screen-container');
		const layoutViewport = document.getElementById('widget-agent-container')!;
		const widget = document.getElementById('widget-sync-screen-wrapper');
		if (screenCotnianer && zcoScreenSync && widget) {
			const layoutHeight = layoutViewport.getBoundingClientRect().height;
			const layoutWidth = layoutViewport.getBoundingClientRect().width;
			const realHeight = layoutHeight - 170; // 667 + 60 + 40
			if (screenSyncState().mode === 'small') {
				const rate = 160 / screenSyncState().size.width > 118 / screenSyncState().size.height ? 118 / screenSyncState().size.height : 160 / screenSyncState().size.width;
				screenCotnianer.style.transform = `scale(${rate})`;
				screenCotnianer.style.transformOrigin = 'left top';
				screenCotnianer.style.left = `${160 / 2 - (screenSyncState().size.width / 2) * rate}px`;
				screenCotnianer.style.top = `0px`; // 减去 header 高度
				zcoScreenSync.setToolHide(false);
			} else {
				const rect = widget.getBoundingClientRect();
				const scale = Math.min(Math.min((rect.height - 100), 667) / screenSyncState().size.height, 1); // realHeight / screenSyncState().size.height > 1 ? 1 : realHeight / screenSyncState().size.height;
				const left = (screenSyncState().size.width - screenSyncState().size.width * scale) / 2;
				console.log('scale:', left, scale, realHeight, screenSyncState().size.height, layoutHeight, layoutWidth, screenSyncState().size.width, rect);
				screenCotnianer.style.transform = `scale(${scale})`;
				screenCotnianer.style.transformOrigin = 'left top';
				screenCotnianer.style.left = left + 'px';
				screenCotnianer.style.top = `60px`; // 减去 header 高度
			}
		}
	};

	/** 结束同屏 */
	const onScreenSyncEnd = () => {
		setScreenSyncState(defaultInitialState);
		isStartScreenSync.current = false;
		console.log(screenSyncState);
		if (!zcoScreenSync) return;
		zcoScreenSync.destory();
		zcoScreenSync = null;
	};

	const initScreenSync = () => {
		if (zcoScreenSync) return;
		console.log('initScreenSync:', screenSyncState().size);

		/**
		 * 接收同屏组件消息，并发送给访客
		 */
		const onScreenSyncMessage = (data: any) => {
			if (data?.subType === 'remote-control-disable') {
				// Message.warning(t('relogin-invalid-account'));
				setErrorMessage(t('disable-remote-control') || '');
				return;
			}
			if (screenSyncState().clientId) {
				ivcs.agent.browsingMark(
					data,
					screenSyncState().clientId || '',
					(success: any) => {
						console.log('发送消息成功！' + data, success);
					},
					(error: any) => {
						console.error('发送消息失败！' + data, error);
					}
				);
			}
		};

		const sendCustomeizeMessage = (data: any, toRole: string) => {
			ivcs.agent.sendCustomMessage(
				data,
				toRole,
				(success: any) => {
					console.log(success);
				},
				(error: any) => {
					console.log(error);
				}
			);
		};

		/** 接收自定义消息 */
		// const receiveCustomizeMessage = 
		ivcs.agent.onCustomMessage((data:any) => {
			console.log('data?.pageStatus ', data.data?.pageStatus);
			// pageStatus: hidden | show
			if (data.data?.pageStatus === 'hidden') {
				setScreenSyncState({ ...screenSyncState(), pageLeave: true });
			} else if (data.data?.pageStatus === 'show') {
				setTimeout(() => {
					setScreenSyncState({ ...screenSyncState(), pageLeave: false });
				}, 1000)
			}
			if (data.data?.pageStatus) return;
			const {type, action, value} = data.data;
			console.log('onCustomMessage:', data.data);
			if (type === 'whiteboard') {
				// type : whiteboard
				zcoScreenSync.setMarkData(data.data)
			}
		});

		// 删除已有的tools-list-wrapper
		let toolsListWrapper = document.getElementById('tools-list-wrapper');
		if (toolsListWrapper) {
			toolsListWrapper.parentNode?.removeChild(toolsListWrapper);
		}

		zcoScreenSync = new ZcoScreenSync('widget-sync-screen-container', {
			isCustomer: false,
			url: null,
			width: screenSyncState().size.width,
			height: screenSyncState().size.height,
			// receiveCustomizeMessage,
			sendCustomeizeMessage,
			onScreenSyncMessage,
			onScreenSyncEnd
		});

		setScaleSize();

		zcoScreenSync.setToolHide(false);

		// 将 tools-list-wrapper 移动到 widget-sync-screen-container 下面
		toolsListWrapper = document.getElementById('tools-list-wrapper');
		const widgetSyncScreenContainer = document.getElementById('widget-sync-screen-wrapper');
		if (toolsListWrapper && widgetSyncScreenContainer && toolsListWrapper.parentNode && toolsListWrapper.parentNode !== widgetSyncScreenContainer) {
			toolsListWrapper.parentNode.removeChild(toolsListWrapper);
			widgetSyncScreenContainer.appendChild(toolsListWrapper);
		}

		console.log('screenSyncRef.current:', zcoScreenSync);
	};

	return (
		<ScreenSyncContext.Provider
			children={children}
			value={{ screenSyncState, setScreenSyncState, startCoBrowsing, initScreenSync, onCoBrowsing, reuqestPages, onScreenSyncEnd, zcoScreenSync }}
		></ScreenSyncContext.Provider>
	);
};

const useScreenSync = () => {
	const context = React.useContext(ScreenSyncContext);
	if (!context) {
		throw new Error('useScreenSync 必须在 AppProvider 中使用');
	}
	return context;
};

export { useScreenSync, ScreenSyncProvider };
